package com.ruoyi.coal.modules.publicAPI.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfStamper;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.imageio.ImageIO;

import com.ruoyi.coal.common.utils.imageUtils;
import com.ruoyi.coal.modules.coalpile.domain.CoalYardHistoryEntity;
import com.ruoyi.coal.modules.coalpile.domain.CoalYardInfoEntity;
import com.ruoyi.coal.modules.coalpile.domain.CutUpEntity;
import com.ruoyi.coal.modules.coalpile.domain.vo.CoalPileInfoVo;
import com.ruoyi.coal.modules.coalpile.domain.vo.PdfVo;
import com.ruoyi.coal.modules.coalpile.mapper.CoalPileInfoDao;
import com.ruoyi.coal.modules.coalpile.mapper.CoalYardHistoryDao;
import com.ruoyi.coal.modules.coalpile.mapper.CoalYardInfoDao;
import com.ruoyi.coal.modules.coalpile.mapper.CutUpDao;
import com.ruoyi.coal.modules.coalpile.service.CoalPileInfoService;
import com.ruoyi.coal.modules.coalpile.service.CoalYardInfoService;
import com.ruoyi.coal.modules.coalpile.service.CutUpService;
import com.ruoyi.coal.modules.coalpile.service.PointService;
import com.ruoyi.coal.modules.minio.MinioConfig;
import com.ruoyi.coal.modules.publicAPI.service.PublicService;
import com.ruoyi.coal.modules.publicAPI.service.StartRadarService;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Service("PublicService")
@DataSource(value = DataSourceType.SLAVE)
public class PublicServiceImpl implements PublicService {
    @Autowired
    private CoalYardInfoDao coalYardInfoDao;

    @Autowired
    private CoalYardHistoryDao coalYardHistoryDao;

    @Autowired
    private CoalYardInfoService coalYardInfoService;

    @Autowired
    private CutUpService cutUpService;

    @Autowired
    private CutUpDao cutUpDao;

    @Autowired
    private CoalPileInfoService coalPileInfoService;

    @Autowired
    private CoalPileInfoDao coalPileInfoDao;

    @Autowired
    private StartRadarService startRadarService;

    @Autowired
    private PointService pointService;

    @Autowired
    private MinioConfig minioConfig;

    @Value("${totalReportImage.urlImage}")
    private String totalReportUrlImage;

    @Value("${pileReportImage.urlImage}")
    private String pileReportUrlImage;

    public Map<String, Object> delDataAndGetMaxMin(Integer id, String upload) {
        CoalYardInfoEntity selectOne = (CoalYardInfoEntity)this.coalYardInfoDao.selectOne((Wrapper)(new QueryWrapper()).eq("name", "导入料堆"));
        if (!StringUtils.isEmpty(selectOne)) {
            this.coalYardInfoDao.deleteById(selectOne.getId());
            this.cutUpDao.delete((Wrapper)(new QueryWrapper()).eq("coal_yard_id", selectOne.getId()));
            List<CoalYardHistoryEntity> coal_yard_id = this.coalYardHistoryDao.selectList((Wrapper)(new QueryWrapper()).eq("coal_yard_id", selectOne.getId()));
            for (CoalYardHistoryEntity coalYardHistoryEntity : coal_yard_id) {
                this.coalYardHistoryDao.deleteById(coalYardHistoryEntity.getId());
                this.coalPileInfoDao.delete((Wrapper)(new QueryWrapper()).eq("history_id", coalYardHistoryEntity.getId()));
            }
        }
        CoalYardInfoEntity queryOne = (CoalYardInfoEntity)this.coalYardInfoDao.selectById(id);
        CoalYardInfoEntity coalYardInfoEntity = new CoalYardInfoEntity();
        BeanUtil.copyProperties(queryOne, coalYardInfoEntity, new String[0]);
        coalYardInfoEntity.setName("导入料堆");
                coalYardInfoEntity.setRemarks("用于计算导入的料堆");
                        coalYardInfoEntity.setAngle(Integer.valueOf(0));
        coalYardInfoEntity.setGround(Double.valueOf(0.0D));
        coalYardInfoEntity.setBaseData(Double.valueOf(0.0D));
        coalYardInfoEntity.setDensity(Double.valueOf(1.0D));
        this.coalYardInfoService.save(coalYardInfoEntity);
        Integer insertedId = coalYardInfoEntity.getId();
        CutUpEntity cutUpEntity = new CutUpEntity();
        cutUpEntity.setCoalYardId(coalYardInfoEntity.getId());
        cutUpEntity.setCoalPileGround(coalYardInfoEntity.getGround());
        cutUpEntity.setName(coalYardInfoEntity.getName());
        cutUpEntity.setCoalPileDensity(coalYardInfoEntity.getDensity());
        cutUpEntity.setCutType(coalYardInfoEntity.getType());
        cutUpEntity.setCoalPileGround(Double.valueOf(0.0D));
        cutUpEntity.setDel(Integer.valueOf(1));
        cutUpEntity.setCoalPileDensity(Double.valueOf(1.0D));
        cutUpEntity.setMeasureType(Integer.valueOf(1));
        this.cutUpService.save(cutUpEntity);
        Map<String, Object> pcdAndPoint = this.startRadarService.getPcdAndPoint(upload);
        return pcdAndPoint;
    }

    public Map<String, String> data(PdfVo pdfVo) throws MalformedURLException {
        Map<String, String> data = new HashMap<>();
        if (pdfVo != null) {
            data.put("fill_2", pdfVo.getMeiName());
            data.put("fill_3", pdfVo.getCoalPileInfoEntity().getName());
            data.put("fill_4", String.valueOf(pdfVo.getCoalPileInfoEntity().getLength()));
            data.put("fill_5", String.valueOf(pdfVo.getCoalPileInfoEntity().getWidth()));
            data.put("fill_6", String.valueOf(pdfVo.getCoalPileInfoEntity().getHeight()));
            data.put("fill_7", String.valueOf(pdfVo.getCoalPileInfoEntity().getArea()));
            data.put("fill_8", String.valueOf(pdfVo.getCoalPileInfoEntity().getVolume()));
            data.put("fill_9", String.valueOf(pdfVo.getCoalPileInfoEntity().getDensity()));
            data.put("fill_10", String.valueOf(pdfVo.getCoalPileInfoEntity().getWeight()));
            data.put("fill_11", " ");
            data.put("fill_12", " ");
            data.put("fill_13", " ");
            Date createTime = pdfVo.getCoalPileInfoEntity().getCreateTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetime = simpleDateFormat.format(createTime);
            data.put("fill_15", datetime);
            data.put("fill_1", pdfVo.getMeiName());
        }
        return data;
    }

    public Map<String, String> dataJinCheng(PdfVo pdfVo, PdfStamper pdfStamper) throws IOException, DocumentException {
        Map<String, String> data = new HashMap<>();
        if (pdfVo != null) {
            Date createTime = pdfVo.getCoalPileInfoEntity().getCreateTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetime = simpleDateFormat.format(createTime);
            data.put("fill_11", pdfVo.getCoalPileInfoEntity().getName());
            data.put("fill_12", datetime);
            data.put("fill_5", String.valueOf(pdfVo.getCoalPileInfoEntity().getVolume()));
            data.put("fill_6", String.valueOf(pdfVo.getCoalPileInfoEntity().getDensity()));
            data.put("fill_7", String.valueOf(pdfVo.getCoalPileInfoEntity().getWeight()));
            data.put("fill_8", String.valueOf(pdfVo.getCoalPileInfoEntity().getLength()));
            data.put("fill_9", String.valueOf(pdfVo.getCoalPileInfoEntity().getWidth()));
            data.put("fill_10", String.valueOf(pdfVo.getCoalPileInfoEntity().getHeight()));
            if (this.pileReportUrlImage.equals("image1")) {
                AcroFields fields = pdfStamper.getAcroFields();
                int pageNo = ((AcroFields.FieldPosition)fields.getFieldPositions("image1").get(0)).page;
                Rectangle signRect = ((AcroFields.FieldPosition)fields.getFieldPositions("image1").get(0)).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();
                String fileName = this.minioConfig.downloadFile(pdfVo.getCoalPileInfoEntity().getUrlImage1(), "jincheng.jpg");
                Image image = Image.getInstance(imageUtils.imgToBase64(pdfVo.getCoalPileInfoEntity().getUrlImage1()));
                PdfContentByte under = pdfStamper.getOverContent(pageNo);
                image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                image.setAbsolutePosition(x, y);
                under.addImage(image);
            }
        }
        return data;
    }

    public void writeToExcel(Integer CoalYardId, Integer historyId) {
        List<CoalPileInfoVo> pdfVo1 = this.coalPileInfoService.getALLByHistoryId(historyId);
        BufferedImage bufferImg = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream("./xmsy.xlsx");
            XSSFWorkbook wb = new XSSFWorkbook(fs);
            XSSFCellStyle title = wb.createCellStyle();
            title.setBorderBottom(BorderStyle.THIN);
            title.setBorderLeft(BorderStyle.THIN);
            title.setBorderTop(BorderStyle.THIN);
            title.setBorderRight(BorderStyle.THIN);
            title.setAlignment(HorizontalAlignment.CENTER);
            title.setVerticalAlignment(VerticalAlignment.CENTER);
            XSSFSheet sheet = wb.getSheetAt(0);
            FileOutputStream out = new FileOutputStream("./xmsy2.xlsx");
            sheet.createFreezePane(2, 0, 2, 0);
            CoalYardInfoEntity byId = (CoalYardInfoEntity)this.coalYardInfoService.getById(CoalYardId);
            CoalPileInfoVo name = new CoalPileInfoVo();
            Double dowmcoal_volume = byId.getBottomVolume();
            Double dowmcoal_density = byId.getBottomDensity();
            Double sumVolume = Double.valueOf(0.0D);
            Double sumWeight = Double.valueOf(0.0D);
            int i;
            for (i = pdfVo1.size() - 1; i >= 0; i--) {
                if (!((CoalPileInfoVo)pdfVo1.get(i)).getName().equals(byId.getName())) {
                    sumVolume = Double.valueOf(sumVolume.doubleValue() + ((Double)Optional.<Double>ofNullable(((CoalPileInfoVo)pdfVo1.get(i)).getVolume()).orElse(Double.valueOf(0.0D))).doubleValue());
                    sumWeight = Double.valueOf(sumWeight.doubleValue() + ((Double)Optional.<Double>ofNullable(((CoalPileInfoVo)pdfVo1.get(i)).getWeight()).orElse(Double.valueOf(0.0D))).doubleValue());
                } else {
                    BeanUtil.copyProperties(pdfVo1.get(i), name, new String[0]);
                }
            }
            for (i = pdfVo1.size() - 1; i >= 0; i--) {
                CutUpEntity cutUpEntity = this.cutUpService.selectCutUpAll(((CoalPileInfoVo)pdfVo1.get(i)).getCutId());
                sheet.shiftRows(2, sheet.getLastRowNum(), 1);
                sheet.createRow(2);
                XSSFRow xSSFRow = sheet.getRow(2);
                if (((CoalPileInfoVo)pdfVo1.get(i)).getName().equals(byId.getName()) && pdfVo1.size() == 1) {
                    xSSFRow.createCell(0).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getName());
                    xSSFRow.createCell(1).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getHeight().doubleValue());
                    xSSFRow.createCell(2).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getVolume().doubleValue());
                    xSSFRow.createCell(3).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getDensity().doubleValue());
                    xSSFRow.createCell(4).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getWeight().doubleValue());
                    if (cutUpEntity.getCutType().intValue() == 1) {
                        xSSFRow.createCell(5).setCellValue(dowmcoal_volume.doubleValue());
                        xSSFRow.createCell(6).setCellValue(dowmcoal_density.doubleValue());
                        xSSFRow.createCell(7).setCellValue(dowmcoal_volume.doubleValue() * dowmcoal_density.doubleValue());
                        xSSFRow.createCell(8).setCellValue(((CoalPileInfoVo)pdfVo1.get(0)).getWeight().doubleValue() + dowmcoal_volume.doubleValue() * dowmcoal_density.doubleValue());
                    } else {
                        xSSFRow.createCell(5).setCellValue("");
                        xSSFRow.createCell(6).setCellValue("");
                        xSSFRow.createCell(7).setCellValue("");
                        xSSFRow.createCell(8).setCellValue(((CoalPileInfoVo)pdfVo1.get(0)).getWeight().doubleValue());
                    }
                    bord((Row)xSSFRow, title, 0, 8);
                } else {
                    if (((CoalPileInfoVo)pdfVo1.get(i)).getName().equals(byId.getName())) {
                        xSSFRow.createCell(0).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getName());
                        xSSFRow.createCell(1).setCellValue("---");
                        xSSFRow.createCell(2).setCellValue(sumVolume.doubleValue());
                        xSSFRow.createCell(3).setCellValue("---");
                        xSSFRow.createCell(4).setCellValue(sumWeight.doubleValue());
                    } else {
                        xSSFRow.createCell(0).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getName());
                        xSSFRow.createCell(1).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getHeight().doubleValue());
                        xSSFRow.createCell(2).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getVolume().doubleValue());
                        xSSFRow.createCell(3).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getDensity().doubleValue());
                        xSSFRow.createCell(4).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getWeight().doubleValue());
                    }
                    bord((Row)xSSFRow, title, 0, 4);
                    if (cutUpEntity.getCutType().intValue() == 1) {
                        if (((CoalPileInfoVo)pdfVo1.get(i)).getName().equals(byId.getName())) {
                            xSSFRow.createCell(5).setCellValue(dowmcoal_volume.doubleValue());
                            xSSFRow.createCell(6).setCellValue(dowmcoal_density.doubleValue());
                            xSSFRow.createCell(7).setCellValue(dowmcoal_volume.doubleValue() * dowmcoal_density.doubleValue());
                            xSSFRow.createCell(8).setCellValue(sumWeight.doubleValue() + dowmcoal_volume.doubleValue() * dowmcoal_density.doubleValue());
                        } else {
                            double pileVolume = Double.parseDouble(String.valueOf(Math.abs(cutUpEntity.getXa1().intValue() - cutUpEntity.getXa2().intValue()) / 360.0D * dowmcoal_volume.doubleValue()));
                            xSSFRow.createCell(5).setCellValue(pileVolume);
                            xSSFRow.createCell(6).setCellValue(dowmcoal_density.doubleValue());
                            xSSFRow.createCell(7).setCellValue(pileVolume * dowmcoal_density.doubleValue());
                            xSSFRow.createCell(8).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getWeight().doubleValue() + pileVolume * dowmcoal_density.doubleValue());
                        }
                    } else if (((CoalPileInfoVo)pdfVo1.get(i)).getName().equals(byId.getName())) {
                        xSSFRow.createCell(5).setCellValue("");
                        xSSFRow.createCell(6).setCellValue("");
                        xSSFRow.createCell(7).setCellValue("");
                        xSSFRow.createCell(8).setCellValue(sumWeight.doubleValue());
                    } else {
                        xSSFRow.createCell(5).setCellValue("");
                        xSSFRow.createCell(6).setCellValue("");
                        xSSFRow.createCell(7).setCellValue("");
                        xSSFRow.createCell(8).setCellValue(((CoalPileInfoVo)pdfVo1.get(i)).getWeight().doubleValue());
                    }
                    bord((Row)xSSFRow, title, 5, 8);
                }
            }
            int rowtime = pdfVo1.size() + 2;
            XSSFRow row = sheet.getRow(rowtime);
            row.getCell(8).setCellValue(((CoalPileInfoVo)pdfVo1.get(0)).getCreateTime());
            String imageUrl = null;
            if (this.totalReportUrlImage.equals("image1")) {
                imageUrl = ((CoalPileInfoVo)pdfVo1.get(pdfVo1.size() - 1)).getUrlImage1();
            } else {
                imageUrl = ((CoalPileInfoVo)pdfVo1.get(pdfVo1.size() - 1)).getUrlImage2();
            }
            this.minioConfig.downloadImage(imageUrl, "./Excel.jpg");
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            if (pdfVo1.size() > 1) {
                URL url = new URL(imageUrl.substring(0, imageUrl.lastIndexOf(".")) + "graphic_symbol.png");
                InputStream graphicSymbol = url.openStream();
                BufferedImage bufferImgSymbol = ImageIO.read(graphicSymbol);
                overlapImage("./Excel.jpg", bufferImgSymbol);
            }
            bufferImg = ImageIO.read(new File("./Excel.jpg"));
            ImageIO.write(bufferImg, "png", byteArrayOut);
            XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch();
            XSSFClientAnchor xssfClientAnchor = new XSSFClientAnchor(0, 0, 255, 255, 1, pdfVo1.size() + 5, 8, pdfVo1.size() + 27);
            xssfClientAnchor.setAnchorType(ClientAnchor.AnchorType.byId(3));
            drawingPatriarch.createPicture(xssfClientAnchor, wb.addPicture(byteArrayOut.toByteArray(), 6));
            out.flush();
            wb.write(out);
            out.close();
            fs.close();
            wb.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void bord(Row row, XSSFCellStyle cellStyle, int m, int j) {
        for (int i = m; i <= j; i++) {
            Cell cell = row.getCell(i);
            cell.setCellStyle((CellStyle)cellStyle);
        }
    }

    public static void overlapImage(String qrcodePath, BufferedImage small) {
        try {
            BufferedImage big = ImageIO.read(new File(qrcodePath));
            Graphics2D gd = big.createGraphics();
            gd.setColor(Color.white);
            gd.dispose();
            Graphics2D g = big.createGraphics();
            int x = 10;
            int y = 10;
            g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
            g.dispose();
            ImageIO.write(big, "jpg", new File(qrcodePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String fileUpload(Integer historyId, File file) {
        FileInputStream input = null;
        MultipartFile mockMultipartFile = null;
        String result = null;
        try {
            CoalYardHistoryEntity coalYardHistoryEntity = (CoalYardHistoryEntity)this.coalYardHistoryDao.selectById(historyId);
            input = new FileInputStream(file);
            MockMultipartFile mockMultipartFile1 = new MockMultipartFile("file", file.getName(), "application/octet-stream", IOUtils.toByteArray(input));
            result = this.minioConfig.upload((MultipartFile)mockMultipartFile1, "xlsx", DateUtil.format(coalYardHistoryEntity.getTime(), "yyyy-MM-dd-HH-mm-ss") + "_" + coalYardHistoryEntity.getCoalYardId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

